<template>
  <div class="product-info-container">
    <!-- 搜索栏 -->
    <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
      <el-input v-model="searchParams.name" style="width: 240px; padding-right: 15px;" placeholder="请输入商品名称" />
      <el-input v-model="searchParams.barcode" style="width: 240px; margin-right: 15px;" placeholder="请输入条码" />
      <el-select v-model="searchParams.categoryId" style="width: 200px; margin-right: 15px;" placeholder="请选择类别" clearable>
        <el-option v-for="category in categoryList" :key="category.id" :label="category.name" :value="category.id" />
      </el-select>
      <el-select v-model="searchParams.status" style="width: 150px; margin-right: 15px;" placeholder="请选择状态" clearable>
        <el-option label="启用" :value="1" />
        <el-option label="禁用" :value="0" />
      </el-select>
      <el-icon @click="getProductList()" style="margin-left: 20px; height: 25px; width: 25px;">
        <Search />
      </el-icon>
      <el-icon style="margin-left: 20px;" @click="resetSearchParams()">
        <Refresh />
      </el-icon>
      <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">创建商品</el-button>
    </div>

    <!-- 商品表格 -->
    <el-table :data="productList" style="width: 100%" stripe border="true">
      <el-table-column label="序号" width="80px" #default="scope" align="center">
        {{ scope.$index + 1 }}
      </el-table-column>
      <el-table-column prop="name" label="商品名称" width="200" align="center" />
      <el-table-column prop="barcode" label="条码" width="150" align="center" />
      <el-table-column label="类别" width="150" align="center">
        <template #default="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column prop="spec" label="规格" width="150" align="center" />
      <el-table-column prop="model" label="型号" width="150" align="center" />
      <el-table-column label="计量单位" width="120" align="center">
        <template #default="scope">
          {{ getUnitName(scope.row.unitId) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" #default="scope" align="center">
        <span v-if="scope.row.status == 1" style="color: green;">启用</span>
        <span v-if="scope.row.status == 0" style="color: red;">禁用</span>
      </el-table-column>
      <el-table-column label="操作" width="300px" fixed="right" align="center" #default="scope">
        <el-button type="primary" plain @click="viewProductDetails(scope.row.id)">详情</el-button>
        <el-button type="warning" plain @click="showEditDialog(scope.row)">修改</el-button>
        <el-button type="danger" plain @click="deleteProduct(scope.row.id)">删除</el-button>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination 
        v-model:current-page="pagination.pageNum" 
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]" 
        layout="total, sizes, prev, pager, next, jumper" 
        :total="pagination.total"
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange" 
      />
    </div>

    <!-- 创建/编辑商品对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑商品' : '创建商品'" width="800px"
      :before-close="handleDialogClose" :close-on-click-modal="false">
      <el-form :model="productForm" label-width="120px" style="padding: 15px 0;" :rules="formRules" ref="productFormRef">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="条码" prop="barcode">
          <el-input v-model="productForm.barcode" placeholder="请输入条码" />
        </el-form-item>
        <el-form-item label="商品类别" prop="categoryId">
          <el-select v-model="productForm.categoryId" placeholder="请选择商品类别" clearable>
            <el-option v-for="category in categoryList" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="spec">
          <el-input v-model="productForm.spec" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="productForm.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="计量单位" prop="unitId">
          <el-select v-model="productForm.unitId" placeholder="请选择计量单位" clearable>
            <el-option v-for="unit in unitList" :key="unit.id" :label="unit.name" :value="unit.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="扩展属性" prop="attributes">
          <el-input v-model="productForm.attributes" type="textarea" placeholder="请输入扩展属性" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="productForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="productForm.remark" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <!-- 商品属性表格 -->
      <div style="margin: 10px 0 0 0;">
        <h4>商品属性</h4>
        <el-table :data="productForm.attributeList || []" style="width: 100%; margin-bottom: 10px;">
          <el-table-column label="序号" width="60" #default="scope" align="center">
            {{ scope.$index + 1 }}
          </el-table-column>
          <el-table-column label="属性名" width="200" #default="scope" align="center">
            <el-select v-model="scope.row.attrName" placeholder="请选择属性名" filterable clearable @change="handleAttrNameChange(scope.$index)">
              <el-option v-for="attrName in attributeNames" :key="attrName" :label="attrName" :value="attrName" />
              <el-option label="+ 新增属性名" value="__NEW__" @click.stop="goToAttributeManagement" />
            </el-select>
          </el-table-column>
          <el-table-column label="属性值" width="200" #default="scope" align="center">
            <el-select v-if="scope.row.attrName && scope.row.attrName !== '__NEW__'" v-model="scope.row.attrValue" placeholder="请选择属性值" filterable clearable>
              <el-option v-for="attrValue in attributeValuesMap[scope.row.attrName] || []" :key="attrValue" :label="attrValue" :value="attrValue" />
              <el-option label="+ 新增属性值" value="__NEW__" @click.stop="goToAttributeManagement" />
            </el-select>
            <el-input v-else-if="scope.row.attrName === '__NEW__'" v-model="scope.row.attrName" placeholder="请输入新属性名" @blur="handleNewAttrName(scope.$index)" />
            <el-input v-else placeholder="请先选择属性名" disabled />
          </el-table-column>
          <el-table-column label="自定义值" width="200" #default="scope" align="center">
            <el-input v-if="scope.row.attrValue === '__NEW__'" v-model="scope.row.customValue" placeholder="请输入新属性值" />
            <span v-else>{{ scope.row.attrValue }}</span>
          </el-table-column>
          <el-table-column label="操作" width="80" #default="scope" align="center">
            <el-button type="danger" size="small" @click="removeAttribute(scope.$index)">删除</el-button>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="small" @click="addAttribute">添加属性</el-button>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 商品详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="商品详情" width="800px" :close-on-click-modal="false">
      <div v-if="productDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商品ID">{{ productDetail.product.id }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ productDetail.product.name }}</el-descriptions-item>
          <el-descriptions-item label="条码">{{ productDetail.product.barcode }}</el-descriptions-item>
          <el-descriptions-item label="商品类别">{{ getCategoryName(productDetail.product.categoryId) }}</el-descriptions-item>
          <el-descriptions-item label="规格">{{ productDetail.product.spec }}</el-descriptions-item>
          <el-descriptions-item label="型号">{{ productDetail.product.model }}</el-descriptions-item>
          <el-descriptions-item label="计量单位">{{ getUnitName(productDetail.product.unitId) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <span v-if="productDetail.product.status == 1" style="color: green;">启用</span>
            <span v-if="productDetail.product.status == 0" style="color: red;">禁用</span>
          </el-descriptions-item>
          <el-descriptions-item label="扩展属性" :span="2">{{ productDetail.product.attributes }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ productDetail.product.remark }}</el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 20px;">
          <h4>商品属性</h4>
          <el-table :data="productDetail.attributes || []" style="width: 100%;">
            <el-table-column label="序号" width="60" #default="scope" align="center">
              {{ scope.$index + 1 }}
            </el-table-column>
            <el-table-column prop="attrName" label="属性名" width="200" align="center" />
            <el-table-column prop="attrValue" label="属性值" align="center" />
          </el-table>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { productApi, productCategoryApi, unitApi, productAttributeApi } from '@/api/product/product'
import { useRouter } from 'vue-router'

// 获取路由实例
const router = useRouter()

// 响应式数据
const productList = ref([])
const categoryList = ref([])
const unitList = ref([])
const attributeNames = ref([]) // 新增：属性名列表
const attributeValuesMap = ref({}) // 新增：属性值映射
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const isEdit = ref(false)
const productFormRef = ref()

// 搜索参数
const searchParams = reactive({
  name: '',
  barcode: '',
  categoryId: null,
  status: null
})

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 商品表单
const productForm = reactive({
  id: null,
  name: '',
  barcode: '',
  categoryId: null,
  spec: '',
  model: '',
  unitId: null,
  attributes: '',
  status: 1,
  remark: '',
  attributeList: []
})

// 商品详情
const productDetail = ref(null)

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品类别', trigger: 'change' }
  ],
  unitId: [
    { required: true, message: '请选择计量单位', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取商品列表
const getProductList = async () => {
  try {
    const params = {
      current: pagination.pageNum,
      size: pagination.pageSize,
      ...searchParams
    }
    
    const response = await productApi.list(params)
    
    if (response && response.records) {
      productList.value = response.records
      pagination.total = response.total
    } else {
      ElMessage.error('获取商品列表失败')
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  }
}

// 获取类别列表
const getCategoryList = async () => {
  try {
    const response = await productCategoryApi.all()
    if (response && Array.isArray(response)) {
      categoryList.value = response
    }
  } catch (error) {
    console.error('获取类别列表失败:', error)
  }
}

// 获取计量单位列表
const getUnitList = async () => {
  try {
    const response = await unitApi.all()
    if (response && Array.isArray(response)) {
      unitList.value = response
    }
  } catch (error) {
    console.error('获取计量单位列表失败:', error)
  }
}

// 获取属性名列表
const getAttributeNames = async () => {
  try {
    const response = await productAttributeApi.getAttributeNames()
    if (response && Array.isArray(response)) {
      attributeNames.value = response
      // 预加载所有属性值
      await preloadAttributeValues(response)
    }
  } catch (error) {
    console.error('获取属性名列表失败:', error)
  }
}

// 预加载所有属性值
const preloadAttributeValues = async (attrNames) => {
  const valuesMap = {}
  for (const attrName of attrNames) {
    try {
      const response = await productAttributeApi.getAttributeValues(attrName)
      if (response && Array.isArray(response)) {
        valuesMap[attrName] = response
      }
    } catch (error) {
      console.error(`获取属性值失败: ${attrName}`, error)
    }
  }
  attributeValuesMap.value = valuesMap
}

// 处理属性名变化
const handleAttrNameChange = async (index) => {
  const item = productForm.attributeList[index]
  if (item.attrName === '__NEW__') {
    item.attrName = ''
    item.attrValue = ''
    item.customValue = ''
  } else if (item.attrName) {
    item.attrValue = ''
    item.customValue = ''
    
    // 如果该属性名的值还没有加载，则加载它
    if (!attributeValuesMap.value[item.attrName]) {
      try {
        const response = await productAttributeApi.getAttributeValues(item.attrName)
        if (response && Array.isArray(response)) {
          attributeValuesMap.value[item.attrName] = response
        }
      } catch (error) {
        console.error(`获取属性值失败: ${item.attrName}`, error)
      }
    }
  }
}

// 处理新增属性名
const handleNewAttrName = (index) => {
  const item = productForm.attributeList[index]
  if (!item.attrName || item.attrName.trim() === '') {
    ElMessage.warning('请输入属性名')
    return
  }
  item.attrName = item.attrName.trim()
  if (item.attrName) {
    item.attrValue = ''
    item.customValue = ''
  }
}

// 跳转到商品属性管理页面
const goToAttributeManagement = () => {
  router.push('/product_attributes')
}

// 获取类别名称
const getCategoryName = (categoryId) => {
  const category = categoryList.value.find(c => c.id === categoryId)
  return category ? category.name : ''
}

// 获取计量单位名称
const getUnitName = (unitId) => {
  const unit = unitList.value.find(u => u.id === unitId)
  return unit ? unit.name : ''
}

// 重置搜索参数
const resetSearchParams = () => {
  Object.assign(searchParams, {
    name: '',
    barcode: '',
    categoryId: null,
    status: null
  })
  pagination.pageNum = 1
  getProductList()
}

// 显示新增对话框
const showAddDialog = () => {
  isEdit.value = false
  Object.assign(productForm, {
    id: null,
    name: '',
    barcode: '',
    categoryId: null,
    spec: '',
    model: '',
    unitId: null,
    attributes: '',
    status: 1,
    remark: '',
    attributeList: []
  })
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = async (row) => {
  isEdit.value = true
  try {
    const response = await productApi.getById(row.id)
    if (response && response.success) {
      Object.assign(productForm, {
        id: response.product.id,
        name: response.product.name,
        barcode: response.product.barcode,
        categoryId: response.product.categoryId,
        spec: response.product.spec,
        model: response.product.model,
        unitId: response.product.unitId,
        attributes: response.product.attributes,
        status: response.product.status,
        remark: response.product.remark,
        attributeList: response.attributes || []
      })
      dialogVisible.value = true
    } else {
      ElMessage.error('获取商品详情失败')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  }
}

// 查看商品详情
const viewProductDetails = async (id) => {
  try {
    const response = await productApi.getById(id)
    if (response && response.success) {
      productDetail.value = response
      detailDialogVisible.value = true
    } else {
      ElMessage.error('获取商品详情失败')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  }
}

// 添加属性
const addAttribute = () => {
  productForm.attributeList.push({
    attrName: '',
    attrValue: '',
    customValue: '' // 新增自定义值字段
  })
}

// 删除属性
const removeAttribute = (index) => {
  productForm.attributeList.splice(index, 1)
}

// 提交表单
const submitForm = async () => {
  try {
    await productFormRef.value.validate()
    
    // 处理属性列表，确保自定义值正确设置
    const processedAttributeList = productForm.attributeList.map(attr => ({
      attrName: attr.attrName,
      attrValue: attr.attrValue === '__NEW__' ? attr.customValue : attr.attrValue
    })).filter(attr => attr.attrName && attr.attrValue) // 过滤掉空的属性
    
    const submitData = {
      ...productForm,
      attributeList: processedAttributeList
    }
    
    const api = isEdit.value ? productApi.update : productApi.add
    const response = await api(submitData)
    
    if (response && response.success) {
      ElMessage.success(isEdit.value ? '商品更新成功' : '商品创建成功')
      dialogVisible.value = false
      getProductList()
    } else {
      ElMessage.error(response?.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  }
}

// 删除商品
const deleteProduct = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      type: 'warning'
    })
    
    const response = await productApi.delete(id)
    
    if (response && response.success) {
      ElMessage.success('删除成功')
      getProductList()
    } else {
      ElMessage.error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  productFormRef.value?.resetFields()
  dialogVisible.value = false
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  getProductList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.pageNum = current
  getProductList()
}

// 初始化
onMounted(() => {
  getProductList()
  getCategoryList()
  getUnitList()
  getAttributeNames() // 初始化属性名列表
})
</script>

<style scoped>
.product-info-container {
  padding: 20px;
  min-height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  padding: 15px 0;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar .el-icon {
  cursor: pointer;
  color: #409eff;
}

.search-bar .el-icon:hover {
  color: #66b1ff;
}
</style>
